// import axios from "axios";
import cookie from './cookie';

export default (mothed = '', data = null) => {
  return new Promise((resolve, reject) => {
    let _data = data;
    if (mothed == 'goPath' && _data && _data.type == 'webView' && _data.param && _data.param.url) {
      _data.param.url =
        (_data.param.url.match(/(http|https):\/\/([\w.]+\/?)\S*/) ? '' : location.origin) +
        _data.param.url;
    }
    _data = _data ? JSON.stringify(data) : null;
    if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
      var bridgeInit = () => {
        return new Promise((_resolve, _reject) => {
          if (window.WebViewJavascriptBridge) {
            _resolve();
          } else {
            var WVJBIframe = document.createElement('iframe');
            WVJBIframe.style.display = 'none';
            WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
            document.documentElement.appendChild(WVJBIframe);
            setTimeout(function () {
              document.documentElement.removeChild(WVJBIframe);
              _resolve();
            }, 0);
          }
        });
      };
      bridgeInit().then((res) => {
        if (
          mothed &&
          window.WebViewJavascriptBridge &&
          window.WebViewJavascriptBridge.callHandler
        ) {
          window.WebViewJavascriptBridge.callHandler(mothed, _data, function (response) {
            var ress = JSON.parse(response);
            if (mothed == 'getToken' && ress['token']) {
              cookie.setCookie('token', ress['token']);
            }
            resolve(response ? ress : '');
          });
        } else {
          reject('请在App端打开');
        }
      });
    } else {
      if (mothed && window.android && window.android[mothed]) {
        var res;
        if (_data) {
          res = JSON.parse(window.android[mothed](_data));
        } else {
          res = JSON.parse(window.android[mothed]());
        }
        if (mothed == 'getToken' && res['token']) {
          cookie.setCookie('token', res['token']);
        }
        resolve(res);
      } else {
        reject('请在App端打开');
      }
    }
  });
};
